package com.aliyun.flashsale.portal.web.config;

import javax.validation.ConstraintViolationException;

import com.aliyun.flashsale.portal.model.ApiResult;
import com.aliyun.flashsale.portal.utils.ExceptionUtils;
import com.aliyun.flashsale.portal.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常建议
 *
 * @date 2024/05/13
 */
@Slf4j
@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ApiResult defaultHandler(Exception e) {
        String message = ExceptionUtils.getRootCauseMessage(e, "系统失败");
        log.error(message, e);
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException cve = (ConstraintViolationException)e;
            return ApiResult.fail(ValidateUtils.buildExceptionMessage(cve));
        }
        return ApiResult.fail(message);
    }

}